package com.fanrenqiji.common.utils;

import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author lijian E-mail:ljz0721cx@163.com
 * @version 创建时间：2015年1月22日 下午4:32:18
 * @description 以静态变量保存Spring ApplicationContext 静态支持类,
 *              可在任何代码任何地方任何时候取出ApplicaitonContext.
 */
public class SpringContextHolder implements ApplicationContextAware {

	private static ApplicationContext applicationContext = null;

	private static Logger logger = LoggerFactory
			.getLogger(SpringContextHolder.class);

	/**
	 * 实现ApplicationContextAware接口的回调方法，设置上下文环境
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		logger.debug("注入ApplicationContext到SpringContextHolder:{}",
				applicationContext);

		SpringContextHolder.applicationContext = applicationContext;
	}

	/**
	 * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name)
			throws NoSuchBeanDefinitionException {
		assertContextInjected();
		return (T) applicationContext.getBean(name);
	}

	/**
	 * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
	 * 
	 * @param requiredType
	 *            注册对象的类型
	 * @return
	 */
	public static <T> T getBean(Class<T> requiredClass)
			throws NoSuchBeanDefinitionException {
		assertContextInjected();
		return applicationContext.getBean(requiredClass);
	}

	/**
	 * 取得存储在静态变量中的ApplicationContext.
	 * 
	 * @return
	 */
	public static ApplicationContext getApplicationContext() {
		assertContextInjected();
		return applicationContext;
	}

	/**
	 * 清除SpringContextHolder中的ApplicationContext为Null.
	 * 在spring配置文件中引入的bean中加入destroy-method="clearHolder"
	 */
	public static void clearHolder() {
		logger.debug("清除SpringContextHolder中的ApplicationContext:"
				+ applicationContext);
		applicationContext = null;
	}

	/**
	 * 检查ApplicationContext不为空. 如果为空会抛出NoSuchBeanDefinitionException 加入共有的校验
	 */
	private static void assertContextInjected() {
		Validate.validState(applicationContext != null,
				"applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
	}
}
